package daoImpl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import utility.Utility;
import dao.CategoryDAO;
import domain.Category;

public class CategoryDaoImpl implements CategoryDAO {
	protected static Logger log = Logger.getLogger(CategoryDaoImpl.class);
	
	@Resource(name = "sessionFactory")
	SessionFactory sessionFactory;

	@Override
	public void addCategory(Category category) {
		log.debug("Adding a new category ...");
		Session session = Utility.getSession(sessionFactory);
		try {
			session.save(category);
			log.debug("Added new category!");
		} catch (Exception ex) {
		} finally {
		}
	}

	@Override
	public void editCategory(Category category) {
		log.debug("Editting an exist category ...");
		Session session = Utility.getSession(sessionFactory);
		Category existCategory = (Category) session.get(Category.class, category.getId());
		existCategory.setName(category.getName());
		existCategory.setProducts(category.getProducts());
		session.save(existCategory);
		log.debug("Updated an exist category");
	}

	@Override
	public void disableCategory(Category category) {
		log.debug("Disabling a category " + category.getName() + "...");
		Session session = Utility.getSession(sessionFactory);
		category.setStatus("Y");
		session.save(category);
		log.debug("Disabled a category : " + category.getName());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Category> searchCategory(String strSearch) {
		log.debug("Searching category with string search " + strSearch + " ...");
		String sql = "FROM Category WHERE name like %:name%";
		Session session = Utility.getSession(sessionFactory);
		Query query = session.createQuery(sql);
		query.setString("name", strSearch);
		List<Category> arrResult = query.list();
		if (CollectionUtils.isNotEmpty(arrResult)) {
			log.debug("Return a list of category with size : " + arrResult.size());
			return arrResult;
		} else {
			log.debug("No records has been found.");
			return null;
		}
	}
}
